
{% from "Makefile.common.jinja" import iquote, src_build_dir with context %}

{#
 #   Macros to transform *.c and *.cpp -> *.o
 #}
{% macro compile(filemap, compiler) %}
{% for source, target in filemap.items() %}
{{ target.path }} : {{ source.path }}
	@echo {{ (source.dirname|basename|pjoin(source.filename))|colorize('yellow') }}
	@mkdir -p {{ target.path|dirname }}
	{{v}}{{ compiler }} {{ iquote(source) }} -o $@ -c {{ source.path }}
include {{ target.path|depsname }}
{% endfor %}
{% endmacro %}

{% macro compile_c(filemap) %}
{{ compile(filemap, e.cc ~ ' ' ~ e.cppflags ~ ' ' ~ e.cflags) }}
{% endmacro %}

{% macro compile_cpp(filemap) %}
{{ compile(filemap, e.cxx ~ ' ' ~ e.cppflags ~ ' ' ~ e.cxxflags) }}
{% endmacro %}

{#
 #   library sources -> *.a
 #}
{% set libs = e.used_libs|libmap(e.build_dir) %}
{% for source_dir, target in libs.items() %}
{% set c = source_dir|glob('*.c')|filemap(target.dirname, e.names.obj) %}
{% set cpp = (source_dir|glob('*.cpp'))|filemap(target.dirname, e.names.obj) %}
{% set libobjs = c.target_paths() + cpp.target_paths() %}
{{ compile_c(c) }}
{{ compile_cpp(cpp) }}
{{ target.path }} : {{ libobjs }}
	@echo {{ ('Linking ' ~ target.filename|basename)|colorize('green') }}
	{{v}}{{ e.ar }} rcs $@ $^
{% endfor %}

{#
 #   *.c -> *.o
 #}
{% set c = e.src_dir|glob('*.c')|filemap(src_build_dir, e.names.obj) %}
{{ compile_c(c) }}

{#
 #   *.cpp -> *.o
 #}
{% set cpp = (e.src_dir|glob('*.cpp') + src_build_dir|glob('*.cpp'))|filemap(src_build_dir, e.names.obj) %}
{{ compile_cpp(cpp) }}

{#
 #   *.o -> elf
 #}
{% set objs = c.target_paths() + cpp.target_paths() + libs.target_paths() %}
{% set elf = e.build_dir|pjoin('firmware.elf') %}
{{ elf }} : {{ objs }}
	@echo {{ 'Linking firmware.elf'|colorize('green') }}
	{{v}}{{ e.cc }} {{ e.ldflags }} -o $@ $^ -lm

{#
 #   elf -> hex
 #}
{{ e.hex_path }} : {{ elf }}
	@echo {{ ('Converting to ' ~ e.hex_filename)|colorize('green') }}
	{{v}}{{ e.objcopy }} -O ihex -R .eeprom $^ $@

include {{ e.deps }}

all : {{ e.hex_path }}
	@true

{#
vim:noexpandtab filetype=jinja
#}
